<template>
  <!--屠宰信息-->
<div style="margin-top: 15px;">
  <table style="width: 40%;">
    <thead></thead>
    <tbody>
      <tr>
        <td style="color:dodgerblue;font-size: 20px;">屠宰信息
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-button type="info" @click="SetUp">设置</el-button>
        </td>
      </tr>
      <tr>
        <td>批次：{{ slaughterData.batch }}</td>
        <td>到厂均重：{{ slaughterData.aveWeight }}公斤</td>
      </tr>
      <tr>
        <td>到厂时间：{{ slaughterData.arriveDate }}</td>
        <td>屠宰时间：{{ slaughterData.slaughterTime }}</td>
      </tr>

      <tr>
      <td style="color:dodgerblue;font-size: 20px;">相关资质</td>
    </tr>
      <span v-for="item in slaughterPicture" :key="item.slaughterId"><img :src="item.pictureName" width="70px" height="70px" />&nbsp;&nbsp;&nbsp;</span>
      <el-button style="width: 100px;height: 100px;" @click="dialogFormVisible=true">+</el-button>
    </tbody>
  </table>
</div>

  <!--企业信息-->
<div style="margin-top: 15px;">
<table style="width: 40%;">
      <thead></thead>
      <tbody>
        <tr>
          <td style="color:dodgerblue;font-size: 20px;">企业信息
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button type="info" @click="dialogFormVisibleAddEnterprise=true">设置</el-button>
          </td>
        </tr>

        <tr>
          <td>公司名称：{{ EnterpriseData.slaughterCompanyName }}</td>
          <td>成立时间：{{ EnterpriseData.establishmentTime }}</td>
        </tr>

        <tr>
          <td>公司地址：{{ EnterpriseData.provinceName }}&nbsp;{{ EnterpriseData.cityName }}&nbsp;{{ EnterpriseData.countyName }}</td>
        </tr>

        <tr>
          <td>公司简介：{{ EnterpriseData.companyProfile }}</td>
        </tr>

        <tr>
          <td style="color:dodgerblue;font-size: 20px;">企业照片</td>
        </tr>
      
        <tr>
          <td>
            <span v-for="item in picData" :key="item.enterpriseId"><img :src="item.pictureName" width="90px" height="90px" />&nbsp;&nbsp;&nbsp;</span>
          </td>
        </tr>
      </tbody>
    </table>
</div>

  <!--表单添加商品产检报告--图片-->
<div>
  <el-dialog v-model="dialogFormVisible" width="500" align-center>
    <el-upload class="avatar-uploader" action="http://localhost:5063/api/PictureManagement/UploadFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="form.pictureNames" :src="form.pictureNames" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</el-dialog>
</div>

<!--表单添加屠宰信息-->
<div>
  <el-dialog v-model="dialogFormVisibleAdd" title="屠宰信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="slaughterForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="批次" prop="batch">
      <el-input v-model="slaughterForm.batch" placeholder="请输入批次" />
    </el-form-item>

    <el-form-item label="到厂均重(公斤)" prop="aveWeight">
      <el-input v-model="slaughterForm.aveWeight" placeholder="请输入到厂均重(公斤)" />
    </el-form-item>

    <el-form-item label="到厂时间" prop="arriveDate">
      <el-date-picker v-model="slaughterForm.arriveDate" type="date" placeholder="请选择到厂日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item label="屠宰时间" prop="slaughterTime">
      <el-date-picker v-model="slaughterForm.slaughterTime" type="date" placeholder="请选择屠宰日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

<!--表单修改屠宰信息-->
<div>
  <el-dialog v-model="dialogFormVisibleUpdate" title="屠宰信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="slaughterForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

      <el-form-item label="批次" prop="batch">
      <el-input v-model="slaughterForm.batch" placeholder="请输入批次" />
    </el-form-item>

    <el-form-item label="到厂均重(公斤)" prop="aveWeight">
      <el-input v-model="slaughterForm.aveWeight" placeholder="请输入到厂均重(公斤)" />
    </el-form-item>

    <el-form-item label="到厂时间" prop="arriveDate">
      <el-date-picker v-model="slaughterForm.arriveDate" type="date" placeholder="请选择到厂日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item label="屠宰时间" prop="slaughterTime">
      <el-date-picker v-model="slaughterForm.slaughterTime" type="date" placeholder="请选择屠宰日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">修改</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

<!--表单添加企业信息-->
<div>
  <el-dialog v-model="dialogFormVisibleAddEnterprise" title="企业信息" width="500" align-center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="enterpriseForm" :rules="enterpriseFormRules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="公司名称" prop="slaughterCompanyName">
      <el-input v-model="enterpriseForm.slaughterCompanyName" placeholder="请输入公司名称" />
    </el-form-item>

    <el-form-item label="公司地址" prop="provinceId">
      <el-select v-model="enterpriseForm.provinceId" placeholder="请选择省份" @change="getCity">
        <el-option v-for="item in provinceData" :key="item.provinceId" :label="item.provinceName" :value="item.provinceId" />
      </el-select>
    </el-form-item>

    <el-form-item label=" " prop="cityId">
      <el-select v-model="enterpriseForm.cityId" placeholder="请选择城市" @change="getCounty">
        <el-option v-for="item in cityData" :key="item.cityId" :label="item.cityName" :value="item.cityId" />
      </el-select>
    </el-form-item>

    <el-form-item label=" " prop="countyId">
      <el-select v-model="enterpriseForm.countyId" placeholder="请选择县">
        <el-option v-for="item in countyData" :key="item.countyId" :label="item.countyName" :value="item.countyId" />
      </el-select>
    </el-form-item>

    <el-form-item label="成立时间" prop="establishmentTime">
      <el-date-picker v-model="enterpriseForm.establishmentTime" type="date" placeholder="请选择成立时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD"/>
    </el-form-item>

    <el-form-item label="公司简介" prop="companyProfile">
      <el-input v-model="enterpriseForm.companyProfile" placeholder="请输入公司简介" />
    </el-form-item>

    <el-form-item style="float:right;">
      <el-button type="primary" @click="addEnterprise">保存</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
</div>

  <!--表单添加企业图片-->
  <div>
  <el-dialog v-model="dialogFormVisible" width="500" align-center>
    <el-upload class="avatar-uploader" action="http://localhost:5063/api/PictureManagement/UploadFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="form.pictureNames" :src="form.pictureNames" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</el-dialog>
</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit, Search, Share, Upload,Plus } from '@element-plus/icons-vue'
import {useRoute,useRouter} from 'vue-router'
import type { UploadProps } from 'element-plus'

const route = useRoute();
const router = useRouter();
//表单校验
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  saveUpdate()
  //屠宰
  getSlaughterData()
  //企业
  getEnterpriseList()

  //省市县
  getProvince()
  getCity()
  getCounty()
})

//商品Form
const form: any = reactive({
  shoppingId: route.query.shoppingId,
  shoppingNameId: '',
  productionBatch: '',
  qgPeriod: '',
  productionLicense: '',
  manufacturingEnterprise: '',
  pictureId: '',
  pictureName: '',
  pictureNames: '',
  createdBy: '',
  createdDate: '',
  deletedBy: '',
  deletedDate: '',
  updatedBy: '',
  updateDate: '',
  isDeleted: '',
  shoppingNames: '',
})

//企业信息
const enterpriseForm: any = reactive({
  shoppingId:route.query.shoppingId,
  slaughterCompanyName: '',
  establishmentTime: '',
  companyProfile: '',
  provinceId: '',
  cityId: '',
  countyId:'',
})

//屠宰Form
const slaughterForm: any = reactive({
  slaughterId:'',
  batch: '',
  aveWeight:'',
  arriveDate:'',
  slaughterTime:'',
  shoppingId:route.query.shoppingId,
  createdBy: '',
  createdDate: '',
  updateBy: '',
  updateData: '',
  deletedBy: '',
  deletedData: '',
  pictureId: '',
  pictureName:''
})

//产品检验报告对话框
const dialogFormVisible = ref(false)

//企业信息添加
const dialogFormVisibleAddEnterprise = ref(false)
//屠宰信息添加
const dialogFormVisibleAdd = ref(false)
//屠宰信息修改
const dialogFormVisibleUpdate = ref(false)
//图片上传
const handleAvatarSuccess = (picUrl: any) => {
  console.log(picUrl);
  
  form.pictureName = picUrl.data;
} 
//上传前判断(文件类型、文件大小)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/gif' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式必须是[JPG,GIF,PNG]格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2MB!')
    return false
  }
  return true
}

//屠宰信息校验
const rules = reactive<FormRules>({
  batch: [
    { required: true, message: '请输入批次', trigger: 'change',},
  ],
  aveWeight: [
    { required: true, message: '请输入到厂均重', trigger: 'blur' },
  ],
  arriveDate: [
    { required: true, message: '请选择到厂时间', trigger: 'blur' },
  ],
  slaughterTime: [
    { required: true, message: '请选择屠宰时间', trigger: 'blur' },
  ],
})


//企业信息校验
const enterpriseFormRules=reactive<FormRules>({
  slaughterCompanyName: [
    { required: true, message: '请输入公司名称', trigger: 'change',},
  ],
  establishmentTime: [
    { required: true, message: '请选择成立时间', trigger: 'blur' },
  ],
  provinceId: [
    { required: true, message: '请选择省份', trigger: 'blur' },
  ],
  cityId: [
    { required: true, message: '请选择市区', trigger: 'blur' },
  ],
  countyId: [
    { required: true, message: '请选择县城', trigger: 'blur' },
  ],
  companyProfile: [
    { required: true, message: '请输入公司简介', trigger: 'blur' },
  ],
})

//反填商品信息
const saveUpdate = () => {
  let Backshopping = {
    shoppingId:form.shoppingId
  }
  axios.post('api/ShoppingManagement/BackInfoShopping',Backshopping).then(res => {
    console.log(res);
    let back = res.data.data;
    form.shoppingId = back.shoppingId;
    form.shoppingNameId = back.shoppingNameId;
    form.shoppingNames = back.shoppingNames;
    form.productionBatch=back.productionBatch;
    form.qgPeriod=back.qgPeriod;
    form.productionLicense=back.productionLicense;
    form.manufacturingEnterprise = back.manufacturingEnterprise;
    form.pictureId = back.pictureId;
    form.pictureName = back.pictureName;   
    form.createdBy = back.createdBy;
    form.createdDate = back.createdDate;
    form.deletedBy = back.deletedBy;
    form.deletedDate = back.deletedDate;
    form.updatedBy = localStorage.userName;
    form.updateDate=Date.now;
    form.isDeleted=back.isDeleted
  }).catch(err => {
    console.log(err);

  })
}

//屠宰信息设置
const SetUp = () => {
  if (slaughterForm.slaughterId == "") {
    //打开屠宰添加对话框
    dialogFormVisibleAdd.value=true
    //添加屠宰信息
  } else {
    //打开屠宰修改对话框
    dialogFormVisibleUpdate.value = true
    //反填信息
    BackslaughterData()
    //修改屠宰信息
  }
}

//添加屠宰信息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let slaughter = {
        batch: slaughterForm.batch,
        aveWeight:slaughterForm.aveWeight,
        arriveDate:slaughterForm.arriveDate,
        slaughterTime:slaughterForm.slaughterTime,
        shoppingId:route.query.shoppingId,
        createdBy: localStorage.userName,
      }
      axios.post('/api/SlaughterManagement/AddSlaughterInfo',slaughter).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("保存成功!")
          //关闭对话框
          dialogFormVisibleAdd.value = false;
        } 
        if (res.data.code == -1) {
          ElMessage.error("保存失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//显示屠宰信息
const slaughterData: any = ref([])
const slaughterPicture:any=ref([])
const getSlaughterData = () => {
  let slaughter = {
    shoppingId:route.query.shoppingId
  }
  axios.post('/api/SlaughterManagement/ShowSlaughterList',slaughter).then(res=>{
    console.log(res);
    slaughterData.value = res.data.data[0];
    slaughterForm.slaughterId = res.data.data[0].slaughterId;
    slaughterPicture.value = res.data.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//反填屠宰信息
const BackslaughterData = () => {
  let slaughter = {
    slaughterId:slaughterForm.slaughterId
  }
  axios.post('/api/SlaughterManagement/BackInfoSlaughter',slaughter).then(res=>{
    console.log(res);
    let SlaughterData = res.data.data;
    slaughterForm.slaughterId = SlaughterData.slaughterId;
    slaughterForm.batch = SlaughterData.batch;
    slaughterForm.aveWeight = SlaughterData.aveWeight;
    slaughterForm.arriveDate = SlaughterData.arriveDate;
    slaughterForm.slaughterTime = SlaughterData.slaughterTime;
    slaughterForm.createdBy = SlaughterData.createdBy;
    slaughterForm.createdDate = SlaughterData.createdDate,
    slaughterForm.updateBy= SlaughterData.updateBy,
    slaughterForm.updateData= SlaughterData.updateData,
    slaughterForm.deletedBy= SlaughterData.deletedBy,
    slaughterForm.deletedData= SlaughterData.deletedData,
    slaughterForm.pictureId= SlaughterData.pictureId,
    slaughterForm.pictureName = SlaughterData.pictureName,
    slaughterForm.isDeleted=SlaughterData.isDeleted
  }).catch(err=>{
    console.log(err);
    
  })    
}

//修改屠宰信息
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let UpdateSlaughter = {
        slaughterId:slaughterForm.slaughterId,
        batch: slaughterForm.batch,
        aveWeight:slaughterForm.aveWeight,
        arriveDate: slaughterForm.arriveDate,
        shoppingId:route.query.shoppingId,
        slaughterTime: slaughterForm.slaughterTime,
        createdBy:slaughterForm.createdBy,
        createdDate : slaughterForm.createdDate,
        updateBy: slaughterForm.updateBy,
        updateData: slaughterForm.updateData,
        deletedBy: slaughterForm.deletedBy,
        deletedData: slaughterForm.deletedData,
        pictureId: slaughterForm.pictureId,
        pictureName: slaughterForm.pictureName,
        isDeleted:slaughterForm.isDeleted
      }
      axios.post('/api/SlaughterManagement/UpdateSlaughter',UpdateSlaughter).then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success("修改成功!")
          //关闭对话框
          dialogFormVisibleUpdate.value = false
          //刷新屠宰信息页面
          getSlaughterData()
        } 
        if (res.data.code == -1) {
          ElMessage.error("修改失败!")
          return
        }
      }).catch(err => {
        console.log(err);
        
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


//省
const provinceData:any=ref([]) 
const getProvince = () => {
  axios.get('/api/ProvinceManagement/GetProvinces').then(res => {
    //console.log(res);
    provinceData.value = res.data.data;
  }).catch(err => {
    console.log(err);

  })
}
  
//市
const cityData:any=ref([]) 
const getCity = () => {
  //清空
  enterpriseForm.cityId = '';
  enterpriseForm.countyId = '';

  axios.get('/api/CityManagement/GetCities', {
    params: {
      provinceId: enterpriseForm.provinceId || null
    }
  }).then(res => {
    //console.log(res);
    cityData.value = res.data.data;
  }).catch(err => {
    console.log(err);

  })
}

//县
const countyData: any = ref([]) 
const getCounty = () => {
  //清空
  enterpriseForm.countyId = '';
  axios.get('/api/CountyManagement/GetCounties', {
    params: {
      cityId: enterpriseForm.cityId || null
    }
  }).then(res => {
    //console.log(res);
    countyData.value = res.data.data;
  }).catch(err => {
    console.log(err);

  })
}  


//企业
//添加屠宰企业信息
const addEnterprise = () => {
  //打开对话框
  dialogFormVisibleAddEnterprise.value = true;
  let enterprise = {
    slaughterCompanyName: enterpriseForm.slaughterCompanyName,
    establishmentTime: enterpriseForm.establishmentTime,
    companyProfile: enterpriseForm.companyProfile,
    provinceId: enterpriseForm.provinceId,
    cityId: enterpriseForm.cityId,
    countyId: enterpriseForm.countyId,
    shoppingId: route.query.shoppingId,
    updateBy:localStorage.userName,
  }
  axios.post('/api/EnterpriseManagement/AddSlaughterEnterpriseInfo', enterprise).then(res => {
    console.log(res);
    if (res.data.code == 1) {
      ElMessage.success("保存成功!")
      //关闭对话框
      dialogFormVisibleAddEnterprise.value = false;
      //刷新企业信息页面
      getEnterpriseList()
    }
    if (res.data.code == -1) {
      ElMessage.error("保存失败!")
      return
    }
  }).catch(err => {
    console.log(err);

  })
}

//查询企业信息
const EnterpriseData: any = ref([])
//图片
const picData:any=ref([])
const getEnterpriseList = () => {
  axios.post('/api/EnterpriseManagement/SearchEnterprise',{}).then(res => {
    console.log(res);
    EnterpriseData.value = res.data.data[0];
    picData.value=res.data.data
  }).catch(err => {
    console.log(err);

  })
}

</script>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>